import base64, pickle
from django_redis import get_redis_connection


def dict_to_str(cookie_dict):
    """
    把字典转换为二进制字符串返回
    :param dict: 字典
    :return: 字符串
    """
    cookie_dict_bytes = pickle.dumps(cookie_dict)
    cookie_str_bytes = base64.b64encode(cookie_dict_bytes)
    return cookie_str_bytes.decode()


def str_to_dict(cookie_str):
    """
    把收到的cookie转换为字典
    :param cookie_str:
    :return:
    """
    cookie_str_bytes = cookie_str.encode()
    cookie_str = base64.b64decode(cookie_str_bytes)
    return pickle.loads(cookie_str)


def merge_cart_cookie_to_redis(request, response, user):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """
    # 获取cookie中的数据
    cookie_str = request.COOKIES.get("cart")
    if cookie_str is None or cookie_str=="":
        return response
    cookie_cart_dict = str_to_dict(cookie_str)
    # 判断是否获取到cookie中的数据,如果没有不执行合并
    if not len(cookie_cart_dict.keys()):
        return response

    # 获取redis 中的数据
    redis_con = get_redis_connection("carts")
    pl = redis_con.pipeline()
    # redis_cart_dict = redis_con.hgetall("cart_%s" % user.id)
    # redis_selecteds = redis_con.smembers('selected_%s' % user.id)

    # 使用redis合并,但是有确定,就是每次循环必须访问一次reids
    for sku_id, cookie_dict in cookie_cart_dict.items():

        pl.hset("cart_%s" % user.id, sku_id, cookie_dict.get("count"))
        pl.sadd("selected_%s" % user.id, sku_id)
        pl.execute()
    response.delete_cookie("cart")
    return response






